package com.js.rest.sys;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.CircleCaptcha;
import cn.hutool.core.util.IdUtil;
import cn.hutool.crypto.digest.BCrypt;
import com.js.common.constant.CacheConst;
import com.js.domian.entity.sys.UserEntity;
import com.js.domian.model.AjaxResult;
import com.js.domian.vo.sys.LoginUser;
import com.js.service.sys.UserService;
import lombok.RequiredArgsConstructor;
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequiredArgsConstructor
public class LoginRest {
    private final CacheManager cacheManager;
    private final UserService userService;

    @PostMapping("/login")
    public AjaxResult login(@RequestBody LoginUser loginUser){
        Cache cache = cacheManager.getCache(CacheConst.CAPTCHA_CODE_KEY);
        Cache.ValueWrapper value = cache.get(loginUser.getUuid());
        if(value == null){
            return AjaxResult.fail("验证码已过期");
        }
        String code = String.valueOf(value.get());
        if(code.equals(loginUser.getCode())){
            UserEntity user = userService.getUserByUserName(loginUser.getUsername());
            if(user == null){
                return AjaxResult.fail("用户不存在");
            }
            //BCrypt.hashpw("123456", BCrypt.gensalt())
            if(BCrypt.checkpw(loginUser.getPassword(), user.getPassword())){
                StpUtil.login(user.getUserName());
                user.setToken(StpUtil.getTokenValue());
                return AjaxResult.ok(user);
            }
            return AjaxResult.fail("密码错误");
        }
        return AjaxResult.fail("验证码错误");
    }

    @GetMapping("/captchaImage")
    public AjaxResult captchaImage(){
        CircleCaptcha captcha = CaptchaUtil.createCircleCaptcha(160, 60, 4, 0);
        // 重新生成code
        captcha.createCode();
        //uuid
        String uuid = IdUtil.fastSimpleUUID();
        //缓存两分钟
        Cache cache = cacheManager.getCache(CacheConst.CAPTCHA_CODE_KEY);
        cache.put(uuid, captcha.getCode());
        return AjaxResult.ok(captcha.getImageBase64Data()).put("uuid", uuid);
    }

    @GetMapping("/logout")
    public AjaxResult logout(){
        StpUtil.logout();
        return AjaxResult.ok();
    }

    public static void main(String[] args) {
        System.out.println(BCrypt.hashpw("admin", BCrypt.gensalt()));
    }
}
